package com.yegs.admin.business.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yegs.admin.business.entity.BaseRole;
import com.yegs.admin.business.entity.BaseUser;
import com.yegs.admin.business.entity.BaseUserRole;
import com.yegs.admin.business.mapper.BaseRoleMapper;
import com.yegs.admin.business.mapper.BaseUserMapper;
import com.yegs.admin.business.mapper.BaseUserRoleMapper;
import com.yegs.admin.business.service.IBaseUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yegs
 * @since 2020-08-22
 */
@Service
public class BaseUserServiceImpl extends ServiceImpl<BaseUserMapper, BaseUser> implements IBaseUserService {

    @Autowired
    private BaseUserMapper baseUserMapper;

    @Autowired
    private BaseUserRoleMapper baseUserRoleMapper;

    @Autowired
    private BaseRoleMapper baseRoleMapper;

    public void saveUserAndRoles(BaseUser baseUser) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(baseUser);
        BaseUser user = baseUserMapper.selectOne(queryWrapper);
        //新增
       if(user==null){
           baseUserMapper.insert(baseUser);
           user =baseUserMapper.selectOne(queryWrapper);
       }else {
           BaseUserRole baseUserRole = new BaseUserRole();
           baseUserRole.setUserId(user.getUserId());
           queryWrapper.setEntity(baseUserRole);
           baseUserRoleMapper.delete(queryWrapper);
       }
        for (BaseRole baseRole:baseUser.getBaseRoles()){
            if(baseRoleMapper.selectById(baseRole.getRoleId())==null){
                throw new Exception("违法菜单");
            }else {
                baseUserRoleMapper.insert(new BaseUserRole(baseUser.getUserId(),baseRole.getRoleId()));
            }
        }
    }

    public BaseUser getUser(String loginId){
        return baseUserMapper.getUser(loginId);
    }

}
